package com.syztb_idea_gsf.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syztb_idea_gsf.dto.Result;
import com.syztb_idea_gsf.entity.TouBFile;
import com.syztb_idea_gsf.mapper.TouBFileMapper;
import com.syztb_idea_gsf.service.ITouBFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class TouBFileServiceImpl extends ServiceImpl<TouBFileMapper, TouBFile> implements ITouBFileService {

    @Override
    public String setFile(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String type = filename.substring(filename.lastIndexOf(".") + 1); // 文件后缀
        TouBFile touBFile = new TouBFile();
        touBFile.setName(filename);
        touBFile.setType(type);
        String url = null;
        InputStream inputStream = file.getInputStream();
        String md5 = SecureUtil.md5(inputStream);
        TouBFile touBFile1 = query().eq("md5", md5).one();

        if (touBFile1 != null) {
            url = touBFile1.getUrl();
        } else {
            // 线上文件处理
            ApplicationHome home = new ApplicationHome(getClass());
            File jarFile = home.getSource();
            if (jarFile != null) {
                // 获取 jar包 的文件路径
                String webPath = jarFile.getParentFile().getPath() + "/touBFile/";
                File newFile = new File(webPath);
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                String finalFileName = uuid + "." + type;
                File targetFile = new File(webPath + finalFileName);
                file.transferTo(targetFile);
                url = webPath + finalFileName;
                touBFile.setUrl(url);
                touBFile.setMd5(md5);
                this.baseMapper.insert(touBFile);
            }
        }
        return url;
    }

    @Override
    public Result deleteFile(String url) {
        int i = baseMapper.deleteByMap(Map.of("url", url));
        if (i>0) {
            return Result.ok("success","删除成功");
        }
        return Result.fail("删除失败");
    }
}
